package com.csnf.servlet;

import com.csnf.entity.Student;
import com.csnf.service.StudentService;
import com.csnf.service.impl.StudentServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;

@WebServlet(name = "StudentServlet",value = {"/StudentServlet","/getAllStudent"})
public class StudentServlet extends HttpServlet {
    StudentService studentService = new StudentServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("students",studentService.getAll());
        req.getRequestDispatcher("stuList.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String name = req.getParameter("name");
        String gender = req.getParameter("gender");
        String sBirthday = req.getParameter("birthday");
        LocalDate birthday = LocalDate.parse(sBirthday);
        String clazz = req.getParameter("clazz");
        String state = req.getParameter("state");
        Student student = new Student(null,name,gender,birthday,clazz,state);
        Boolean flag =false;
        try {
            studentService.addStudent(student);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (flag) {
            req.setAttribute("msg","失败");
        }else{
            req.setAttribute("msg","成功");
        }
        req.getRequestDispatcher("msg.jsp").forward(req,resp);
    }
}
